package android.bluebox.view;

import android.app.Activity;
import android.bluebox.R;
import android.bluebox.model.KeyCrypto;
import android.bluebox.model.PasswordCrypto;
import android.bluebox.model.StaticBox;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ChangePasswordView extends Activity {
	
	EditText edtCurrentPassword;
	EditText edtNewPassword;
	EditText edtConfirmPassword;
	EditText edtRemindPassword;
	
	Button btnUpdate;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.changingpassword);
		
		edtCurrentPassword = (EditText) findViewById(R.id.changepassword_old);
		edtNewPassword = (EditText) findViewById(R.id.changepassword_new);
		edtConfirmPassword = (EditText) findViewById(R.id.changepassword_confirm);
		edtRemindPassword = (EditText) findViewById(R.id.changepassword_remind);
		
		btnUpdate = (Button) findViewById(R.id.changepassword_update);
		btnUpdate.setOnClickListener(update);
		
		edtRemindPassword.setText(StaticBox.dbBox.getRemind());
		
	}
	
	protected void updatePassword(String newPassword) {
		
		String encryptedKey = StaticBox.dbBox.getSystemKey();
		String key = StaticBox.passwordCrypto.decrypt(encryptedKey);
		
		StaticBox.passwordCrypto = new PasswordCrypto();
		StaticBox.passwordCrypto.firstInit(newPassword);
		encryptedKey = StaticBox.passwordCrypto.encrypt(key);
		StaticBox.dbBox.updateSystemKey(encryptedKey);
		
		StaticBox.keyCrypto = new KeyCrypto();
		StaticBox.keyCrypto.init(StaticBox.passwordCrypto);
	}
	
	protected void updateRemind() {
		StaticBox.dbBox.updateSystemRemind(edtRemindPassword.getText().toString());
	}
	
	protected OnClickListener update = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			String currentPassword = edtCurrentPassword.getText().toString();
			if (!StaticBox.passwordCrypto.checkPassword(currentPassword)) {
				StaticBox.makeToast(getBaseContext(), "Wrong current password");
				return;
			}
			
			String newPassword = edtNewPassword.getText().toString();
			String confirmPassword = edtConfirmPassword.getText().toString();
			if (!newPassword.equals(confirmPassword)) {
				StaticBox.makeToast(getBaseContext(), "New password does not match with confirm password");
				return;
			}
			
			updatePassword(newPassword);
			updateRemind();
			StaticBox.makeToast(getBaseContext(), "Update password successfully");
			finish();
		}
	};
}
